<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/1/12
 * Time: 14:25
 */

namespace YMApi\Controller;
use Think\Controller;
use Think\Crypt\Driver\Think;


class OpensearchController extends Controller{
    protected $client;
    protected $category_id;
    protected $app_name = 'sdx';
    protected $wid = 8;
    protected $origin;
    protected $brand_id;
    protected $cat_id;

    protected function _initialize()
    {
        header("Access-Control-Allow-Origin: *");
        $opts = array('host'=>"http://opensearch-cn-hangzhou.aliyuncs.com");
        $this->client = new \Vendor\OpenSearch\CloudsearchClient(C('ALIYUN_AKID'), C('ALIYUN_AKSECRET'), $opts, "aliyun");
    }


    //搜索结果列表
    public function lists(){
        $keyword = I('keyword'); //搜索关键词
        $sort_field = I('sort_field');  //排序字段（价格：shop_price ；评论：comment ）
        $sort_type = I('sort_type'); //排序类型（1:升序；2：降序）
        $page_num = I('page',1, 'int'); //分页
        $cat_id = I('cat_id', 0, 'int');//分类id （一级分类id）
        $this->wid = I('wid',8, 'int');
        $user_id = I('uid',0, 'int');
        $this->origin = I('origin'); //产地（筛选） 多个用 '|'分隔  如 香港|俄罗斯
        $this->brand_id = I('brand_id'); //品牌id（筛选） 多个用 '|'分隔  如 356|1128

        if($cat_id) $this->set_cat_id($cat_id);

        if(!$keyword || !$this->wid) returnApiError('参数有误');
        if($sort_type){
            if($sort_type == 1)
                $sort_type = '+';
            elseif($sort_type == 2)
                $sort_type = '-';
            else
                returnApiError('sort_type参数有误');
        }

        //    	统计搜索热词
        $hotId = I('post.hot_id', 0, 'intval');
        if(!empty($hotId)){
            $hotModel = D('SearchHot');
            $hotModel->add_search_hot_count($hotId);
        }

        //记录搜索记录
        if(!empty($keyword)){
            $search_data = array();
            $search_data['uid'] = $user_id;
            $search_data['keyword'] = $keyword;
            $search_data['searchengine'] = "ECTouch";
            $search_data['create_time'] = gmtime();
            $search = M('search_keyword');
            $search->add($search_data);
        }


        $firstpage = ($page_num-1) *C("page_size");

        $search_list = $this->get_search_list($keyword, $firstpage, $sort_field, $sort_type);

        $id_list = $this->get_goods_id($search_list['items']);
        if(!$id_list) returnApiError('没有数据');

        $goods_list = D('Goods')->get_search_goods_by_id(implode(',', $id_list), $user_id, $this->wid);

        $return_data = array();
        $pagecount = ceil($search_list['total']/C("page_size"));

        if($pagecount <= $page_num){
            //判断是否为最后一页
            $return_data['is_bottom'] = 1;
        }else{
            $return_data['is_bottom'] = 0;
        }
        $return_data['total'] = $search_list['total'];
        $return_data['page'] = array(
            'firstpage' => $firstpage,
            'pagecount' => $pagecount,
            'pagesize' =>C("page_size")
        );
        $return_data['goodssaleslist'] = $goods_list;
        $return_data['origin_list'] = $this->get_origin($keyword);
        $return_data['brand_list'] = $this->get_brand($keyword);
        $return_data['catelist'] = $this->get_category($keyword);
        //print_r($return_data);exit;
        returnApiSuccess($return_data);
    }

    //设置当前一级分类id下的所有子分类id
    protected function set_cat_id($cat_id){
        $cat_list = D('Category')->findCategoryByCatId($cat_id);
        foreach ($cat_list as $value){
            $id_list[] = $value['cat_id'];
        }
        $this->cat_id = implode('|',$id_list);
    }

    protected function get_goods_id($data){
        $id_list = array();
        foreach ($data as $key=>$value){
            $id_list[] = $value['goods_id'];
        }
        return $id_list;
    }

    //获取开放搜索 - 搜索列表结果
    protected function get_search_list($keyword, $start_offset, $sort_field='', $sort_type=''){
        $search = new \Vendor\OpenSearch\CloudsearchSearch($this->client);
        $search->addIndex($this->app_name);
        $search->setHits(C("page_size"));  //返回条数
        $search->setStartHit($start_offset);  //设置返回结果的offset偏移量(从第几条开始)
        $search->setQueryString("keyword:'$keyword'"); // 指定搜索关键词// AND (origin:'俄罗斯' OR origin:'塞浦路斯')
        if($sort_field){
            $sort_type = $sort_type ? $sort_type : '-';
            if($sort_field == 'shop_price')
                $search->addSort("shop_price", $sort_type);
            elseif($sort_field == 2)
                $search->addSort("comment", $sort_type);
            else
                die('sort_field参数有误');
        }
        $search->addFilter('is_on_sale=1');
        $search->addFilter('is_alone_sale=1');
        $search->addFilter('is_delete=0');

        //品牌筛选
        if($this->brand_id){
            $search->addFilter('contain(brand_id, "'.$this->brand_id.'")');
        }

        //产地筛选
        if($this->origin){
            $search->addFilter('contain(origin, "'.$this->origin.'")');
        }

        //分类筛选
        if($this->cat_id){
            $search->addFilter('contain(cat_id, "'.$this->cat_id.'")');
        }
        $search->addSort("real_num", '-');
        $search->addFilter('wid='.$this->wid);
        $search->setFormat("json");

        $json = $search->search();
        $result = json_decode($json,true);

        //print_r($result);exit;
        return $result['result'];
    }

    //获取当前搜索 - 品牌列表
    protected function get_brand($keyword){
        $brand_list = array();
        $data = $this->get_search_type($keyword, 'get_brand');
        foreach ($data['items'] as $key=>$value){
            $brand_list[$key]['id'] = $value['brand_id'];
            $brand_list[$key]['brand_name'] = $value['brand_name'];
        }
        return $brand_list;
    }

    //获取当前搜索 - 产地列表
    protected function get_origin($keyword){
        $origin_list = array();
        $data = $this->get_search_type($keyword, 'get_origin');
        foreach ($data['items'] as $key=>$value){
            if($value['origin'])
                $origin_list[] = $value['origin'];
        }
        rsort($origin_list);
        return $origin_list;
    }

    //获取当前搜索 - 分类列表
    protected function get_category($keyword){
        $category_list = array();
        $data = $this->get_search_type($keyword, 'get_category');
        foreach ($data['items'] as $key=>$value){
            $category_id[] = $value['cat_id'];
        }
        $map['cat_id'] = array('in', implode(',',$category_id));
        $map['is_show'] = array('neq', 0);

        $this->get_category_son_id($map);

        $category_list = $this->assoc_unique($this->category_id, 'cat_id');

        return $category_list;
    }



    //获取开放搜索 - 搜索类型
    protected function get_search_type($keyword, $key){
        $search = new \Vendor\OpenSearch\CloudsearchSearch($this->client);
        $search->addIndex($this->app_name);
        $search->setHits(500);
        $search->setQueryString("keyword:'$keyword'");
        $search->addFilter('is_on_sale=1');
        $search->addFilter('is_alone_sale=1');
        $search->addFilter('is_delete=0');
        $search->addFilter('brand_id!=0');
        $search->addFilter('wid='.$this->wid);
        //$search->addFilter('is_show!=0');
        //$search->addFilter('is_show_1!=0');

        switch ($key){
            case 'get_brand':
                $search->addSort("brand_id", '+');
                $search->addDistinct('brand_id', 1, 1, 'false', '', 'true');
                break;
            case 'get_origin':
                $search->addDistinct('origin', 1, 1, 'false', '', 'true');
                break;
            case 'get_category':
                $search->addDistinct('cat_id', 1, 1, 'false', '', 'true');
                break;
            default:
                return;
        }
        $search->setFormat("json");
        $json = $search->search();
        $result = json_decode($json,true);
        //print_r($result);exit;
        return $result['result'];
    }

    //搜索下拉词
    public function get_pulldown(){
        $keyword = I('keyword');
        $num = I('num',10);
        $num = $num > 10 ? 10 : $num;
        if(!$keyword || !$num){
            returnApiError('参数错误');
        }

        $suggest = new \Vendor\OpenSearch\CloudsearchSuggest($this->client);
        $suggest->setIndexName($this->app_name);
        $suggest->setSuggestName('sdx');
        $suggest->setHits($num);		//返回条数
        $suggest->setQuery($keyword);			//查询关键词
        $result = json_decode($suggest->search(), true);

        if($result['suggestions'])
            returnApiSuccess(array('pulldown_list'=>$result['suggestions']));
        else
            returnApiError('无数据');
    }


    //递归获取所有父级id
    protected function get_category_son_id($map){
        $category = M('category')->field('cat_id,cat_name,parent_id')->where($map)->select();
        foreach ($category as $value){

            if($value['parent_id']){
                $this->get_category_son_id('is_show!=0 and cat_id='.$value['parent_id']);
            }else{
                $this->category_id[]=$value;
            }

        }

    }

    //过滤重复
    protected function assoc_unique($arr, $key) {
        $tmp_arr = array();

        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                unset($arr[$k]);
            } else {
                $tmp_arr[] = $v[$key];
                $list[] = $arr[$k];
            }
        }

        return $list;
    }

}